package com.sprite.framework.entity.util;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.sprite.utils.UtilCollection;
import com.sprite.utils.UtilXml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import com.sprite.framework.entity.EntityException;
import com.sprite.framework.entity.EntityObject;

/**
 * 实体数据加载器
 * @author Jack
 */
public class EntityDataReader {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public EntityDataReader(){
	}


	public List<EntityGroup> loadToEntity(Document document){
		if(document == null){
			return Collections.emptyList();
		}
		Element docElement = document.getDocumentElement();
		if(!"entity-data".equals(docElement.getTagName())){
			throw new IllegalArgumentException("entity data resource error");
		}
		
		return loadToEntity(docElement);
	}
	
	public List<EntityGroup> loadToEntity(Element docElement){
		
		docElement.normalize();
		Node curChild = docElement.getFirstChild();

		List<EntityGroup> entities = new LinkedList<>();
		if(curChild != null){
			EntityGroup defaultGroup = new EntityGroup();
			entities.add(defaultGroup);
			do{
				if (curChild.getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) curChild;
					String nodeName = curChild.getNodeName();
					if("entity-group".equals(nodeName)){
						List<EntityGroup> list = loadToEntity(element);
						entities.addAll(list);
					}else if("entity".equals(nodeName)){
						EntityObject value = null;
						try {
							value = this.toEntity(element);
						} catch (EntityException e) {
							logger.error("Transfer entity data to Entity", e);
						}

						if (value != null) {
							defaultGroup.addEntity(value);
						}
					}
					
				}
			}while((curChild = curChild.getNextSibling()) != null);
		}
		
		return entities;
	}

	/**
	 * 将节点转成对象
	 * @param element xml节点
	 * @return 实体对象
	 * @throws EntityException 实体异常
	 */
	public EntityObject toEntity(Element element) throws EntityException{
		if (element == null) {
			return null;
		}

		List<Element> fields = UtilXml.childElementList(element, "field");


		if(UtilCollection.isEmpty(fields)){
			return null;
		}

		EntityObject entityObject = new EntityObject();
		entityObject.setEntityName(element.getAttribute("entityName"));
		for(Element field: fields){
			entityObject.put(field.getAttribute("name"), field.getAttribute("value"));
		}

		return entityObject;
	}
}
